import { AppDataSource } from "../data-source";
import { NextFunction, Request, Response } from "express";
import { Article } from "../entity/Article";
import { User } from "../entity/User";
import { jwtEncryptionVerify } from "../utils/jwt.js";
import { removeKeys } from "../utils/utils.js";

export class ArticleController {
  private articleRepository = AppDataSource.getRepository(Article);
  private userRepository = AppDataSource.getRepository(User);
  // 保存文章接口
  async saveArticle(request: Request, response: Response, next: NextFunction) {
    let plaintext = jwtEncryptionVerify(
      request.headers["authorization"]?.split(" ")[1]
    );
    let user = await this.userRepository.findOne({
      where: { userName: plaintext.username },
    });
    if (!user) {
      console.log("用户信息错误，请登录");
    }
    const article = Object.assign(new Article(), {
      ...request.body,
      user,
    });
    try {
      let result = await this.articleRepository.save(article);
      if (result) {
        response.json({
          code: "0000",
          data: {},
          msg: "保存成功",
        });
        return;
      }
    } catch (error) {
      console.log("保存接口报错了", error);
    }
  }
  // 查询文章（文章id、文章标题、查询所有文章）
  async queryArticle(request: Request, response: Response, next: NextFunction) {
    let articleList, user;
    let { userName, id } = request.query;
    if (userName) {
      user = await this.userRepository.findOne({
        where: { userName },
      });
      articleList = user.article;
    } else if (id) {
      articleList = await this.articleRepository.findOne({
        where: { id },
      });
    } else {
      articleList = await this.articleRepository.find();
    }
    return {
      code: "0000",
      msg: "成功",
      data: {
        article: articleList,
      },
    };
  }
  // 删除文章
  async removeArticle(
    request: Request,
    response: Response,
    next: NextFunction
  ) {
    const { id } = request.body;
    let plaintext = jwtEncryptionVerify(
      request.headers["authorization"]?.split(" ")[1]
    );
    let user,
      flag = false;
    if (plaintext.role != "root") {
      //不是管理员只能删除自己名下的文章
      user = await this.userRepository.findOne({
        where: { userName: plaintext.username },
      });
      user.article.filter((item) => {
        if (item.id != id) {
          return item;
        } else {
          flag = true;
        }
      });
      if (!flag) {
        return {
          code: "0009",
          msg: "未查到相关文章",
        };
      } else {
        const articles = await this.articleRepository.findOne({
          where: { id },
        });
        let article = await this.articleRepository.remove(articles);
        if (article) {
          return {
            code: "0000",
            msg: "删除成功",
            data: null,
          };
        }
      }
    } else {
      //超级管理员不用关注是谁的文章
      const articles = await this.articleRepository.findOne({
        where: { id },
      });
      let article = await this.articleRepository.remove(articles);
      if (article) {
        return {
          code: "0000",
          msg: "删除成功",
          data: null,
        };
      }
    }
  }
  // 更新文章
  async updateArticle(
    request: Request,
    response: Response,
    next: NextFunction
  ) {
    let body = request.body;
    let plaintext = jwtEncryptionVerify(
      request.headers["authorization"]?.split(" ")[1]
    );
    let article = await this.articleRepository.findOne({
      where: { id: body.id },
    });
    let user = await this.userRepository.findOne({
      where: { userName: plaintext.username },
    });
    let flag = user.article.some((item) => item.id == body.id);
    if (!article || !flag) {
      return {
        code: "0009",
        msg: "抱歉未查到相关文章",
        data: null,
      };
    }
    let newArticle = Object.assign(article, removeKeys(["id"], body));
    try {
      await this.articleRepository.save(newArticle);
      return {
        code: "0000",
        msg: "更新成功",
        data: null,
      };
    } catch (error) {
      console.log(error);
      return {
        code: "0009",
        msg: "更新失败",
        data: newArticle,
      };
    }
  }
  // 分类查询
  async classificationArticle(
    request: Request,
    response: Response,
    next: NextFunction
  ) {
    let articleRepositoryTag;
    let classification = request.query.classification;
    if (classification) {
      articleRepositoryTag = await this.articleRepository.find({
        where: { classification },
      });
    }
    return {
      code: "0000",
      msg: "成功",
      data: {
        article: articleRepositoryTag,
      },
    };
  }
}
